package org.hepeng.workx.spring.security.web;

import org.springframework.context.ApplicationContext;
import org.springframework.security.config.annotation.ObjectPostProcessor;
import org.springframework.security.web.access.intercept.FilterSecurityInterceptor;

import java.util.Objects;

/**
 * @author he peng
 */
public class ReplaceDefaultSecurityMetadataSourceObjectPostProcessor implements ObjectPostProcessor<FilterSecurityInterceptor> {

    private SecurityConfigAttributeLoader securityConfigAttributeLoader;
    private ApplicationContext context;

    public ReplaceDefaultSecurityMetadataSourceObjectPostProcessor(ApplicationContext context , SecurityConfigAttributeLoader securityConfigAttributeLoader) {
        this.context = context;
        this.securityConfigAttributeLoader = securityConfigAttributeLoader;
    }

    @Override
    public <O extends FilterSecurityInterceptor> O postProcess(O object) {
        FilterSecurityInterceptor interceptor = object;

        DataProvideFilterInvocationSecurityMetadataSource securityMetadataSource = null;
        try {
            securityMetadataSource = context.getBean(DataProvideFilterInvocationSecurityMetadataSource.class);
        } catch (Exception e) {

        }
        if (Objects.isNull(securityMetadataSource)) {
            securityMetadataSource = new DataProvideFilterInvocationSecurityMetadataSource(
                    interceptor.obtainSecurityMetadataSource() , securityConfigAttributeLoader);
        }
        interceptor.setSecurityMetadataSource(securityMetadataSource);
        return (O) interceptor;
    }
}
